<?php

namespace Cck\ArticlesSystem\Http\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;

/**
 * @property string $name
 * @property string $slug
 * @property string $catalogue
 * @property boolean $recommend
 * @property string $seo_title
 * @property string $seo_keywords
 * @property string $seo_description
 * 
 * @property-read Taggable[]|Collection $taggables
 * @property-read Article[]|Collection $articles
 * 
 */
class Tag extends Model
{
    protected $table = 'tags';

    protected $fillable = [
        'name', 'slug', 'catalogue', 'recommend', 'seo_title', 'seo_keywords', 'seo_description'
    ];

    protected $casts = [
        'recommend' => 'boolean'
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function (Tag $tag) {
            if (!$tag->catalogue) {
                $setting = settings('tag_catalogue_length', ['min' => 3, 'max' => 5]);
                [$min, $max] = [$setting['min'], $setting['max']];
                switch (strtolower(settings('tag_catalogue_generate_rule', 'random_numbers'))) {
                    case 'random_numbers':
                        $tag->catalogue = randomNumbers($min, $max);
                        break;
                    case 'random_letters':
                        $tag->catalogue = randomLetters($min, $max);
                        break;
                    case 'random_letters_and_numbers':
                        $tag->catalogue = randomNumbersAndLetters($min, $max);
                        break;
                    case 'root_catalogue':
                    default:
                        $tag->catalogue = '';
                        break;
                }
            }

            if (!$tag->slug) {
                $setting = settings('tag_slug_length', ['min' => 3, 'max' => 5]);
                [$min, $max] = [$setting['min'], $setting['max']];

                switch (strtolower(settings('tag_slug_generate_rule', 'id'))) {
                    case 'id':
                        $tag->slug = self::query()->max('id') + 1;
                    case 'random_letters_and_numbers':
                        $tag->slug = randomNumbersAndLetters($min, $max);
                    case 'random_numbers':
                        $tag->slug = randomNumbers($min, $max);
                    case 'random_letters':
                    default:
                        $tag->slug = randomLetters($min, $max);
                }
            }
        });
    }

    public function taggables()
    {
        return $this->hasMany(Taggable::class, 'tag_id', 'id');
    }

    public function articles()
    {
        return $this->morphToMany(Article::class, 'taggable', 'taggables')->using(Taggable::class);
    }
}
